import {PageContainer} from '@ant-design/pro-components';
import {Button, Card, Col, Image, message, Row, Space, Tabs, Tag, Typography} from 'antd';
import React, {useEffect, useState} from 'react';
import {downloadGeneratorByIdUsingGet, getGeneratorVoByIdUsingGet} from "@/services/backend/generatorController";
import {useParams} from "@@/exports";
import moment from "moment";
import {DownloadOutlined, EditOutlined} from "@ant-design/icons";
import AuthorInfo from "@/pages/Generator/Detail/components/AuthorInfo";
import FileConfig from "@/pages/Generator/Detail/components/FileConfig";
import ModelConfig from "@/pages/Generator/Detail/components/ModelConfig";
import {COS_HOST} from "@/constants";
import {saveAs} from "file-saver";
import {useModel} from "@umijs/max";
import {Link} from "umi";


/**
 * 生成器详情页面
 * @constructor
 */
const GeneratorDetailPage: React.FC = () => {

  const {id} = useParams(); // 从url的路由中获取id
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<API.GeneratorVO>({}); // 给data默认值为{} 保证渲染时如果没有数据也可以拿到空值
  const {initialState} = useModel('@@initialState'); // 获取前端的全局状态
  const {currentUser} = initialState ?? {}; // 从全局状态中获取当前登录用户信息
  const my = data.userId === currentUser?.id;

  /**
   * 加载数据
   */
  const loadData = async () => {
    if (!id) {
      return;
    }
    setLoading(true);
    try {
      const res = await getGeneratorVoByIdUsingGet({id: Number(id)});
      setData(res.data ?? {});
    } catch (e: any) {
      message.error("获取数据失败," + e.message);
    }
    setLoading(false);
  };

  // id改变时执行方法来渲染页面
  useEffect(() => {
    if (id) {
      loadData();
    }
  }, [id]);

  /**
   * 标签列表
   * @param tags 标签数组，允许为空
   */
  const tagListView = (tags?: string[]) => {
    if (!tags) {
      return <></>;
    }
    return (<div style={{marginBottom: 8}}>{tags.map(tag => (<Tag key={tag}>{tag}</Tag>))}</div>);
  };

  /**
   * 下载按钮(控制权限 登录才可以下载)
   */
  const downloadButton = data.distPath && currentUser && (
    <Button
      icon={<DownloadOutlined/>}
      onClick={async () => {
        const blob = await downloadGeneratorByIdUsingGet({id: Number(id)}, {responseType: "blob"});
        // 使用file-saver下载文件
        const fullPath = COS_HOST + data.distPath;
        saveAs(blob, fullPath.substring(fullPath.lastIndexOf('/') + 1));
      }}
    >下载</Button>
  );

  /**
   * 编辑按钮(控制权限 本人才可以编辑)
   */
  const editButton = my && (
    <Link to={`/generator/update?id=${data.id}`}>
      <Button icon={<EditOutlined/>}>编辑</Button>
    </Link>
  );

  return (
    <PageContainer title={<></>} loading={loading}>
      <Card>
        <Row justify="space-between" align="middle" gutter={[32, 32]}>
          <Col flex="auto">
            <Space size="large">
              <Typography.Title level={4}>{data.name}</Typography.Title>
              {tagListView(data.tags)}
            </Space>
            <Typography.Paragraph>{data.description}</Typography.Paragraph>
            <Typography.Paragraph type="secondary">
              创建时间：{moment(data.createTime).format('YYYY-MM-DD HH:mm:ss')}
            </Typography.Paragraph>
            <Typography.Paragraph type="secondary">基础包：{data.basePackage}</Typography.Paragraph>
            <Typography.Paragraph type="secondary">版本：{data.version}</Typography.Paragraph>
            <Typography.Paragraph type="secondary">作者：{data.author}</Typography.Paragraph>
            <div style={{marginBottom: 24}}></div>
            <Space size="middle">
              <Link to={`/generator/use/${data.id}`}>
                <Button type="primary">立即使用</Button>
              </Link>
              {downloadButton}
              {editButton}
            </Space>
          </Col>
          <Col flex="400px">
            <Image src={data.picture}/>
          </Col>
        </Row>
      </Card>
      <div style={{marginBottom: 24}}></div>
      <Card>
        <Tabs size="large" defaultActiveKey="fileConfig"
              onChange={() => {
              }}
              items={[
                {
                  key: 'fileConfig',
                  label: '文件配置',
                  children: <FileConfig data={data}/>,
                },
                {
                  key: 'modelConfig',
                  label: '模型配置',
                  children: <ModelConfig data={data}/>,
                },
                {
                  key: 'authorInfo',
                  label: '作者信息',
                  children: <AuthorInfo data={data}/>,
                },
              ]}
        />
      </Card>
    </PageContainer>
  );
};

export default GeneratorDetailPage;
